import os

from xlutils.filter import BaseReader,BaseFilter,BaseWriter,process

class Reader(BaseReader):

    def __init__(self,names, obj):
        self.names = names
        self.obj = obj
    def get_filepaths(self):
        return [os.path.abspath(self.obj.file.path)]

    def __call__(self,filter):
        filter.start()
        for workbook,filename in self.get_workbooks():
            filter.workbook(workbook,filename)
            x=0
            for sheet_x in range(0, len(self.names)):
                sheet = workbook.sheet_by_index(0)
                filter.sheet(sheet,self.names[x])
                x=x+1
                for row_x in xrange(sheet.nrows):
                    filter.row(row_x,row_x)
                    for col_x in xrange(sheet.ncols):
                        filter.cell(row_x,col_x,row_x,col_x)
                if workbook.on_demand:
                    workbook.unload_sheet(0)
        filter.finish()

class Writer(BaseWriter):
    def get_stream(self,filename):
        return file(filename,'wb')

class Filter(BaseFilter):

    pending_row = None
    wtrowxi = 0
    z=0

    def __init__(self,counts):
        self.counts = counts

    def workbook(self,rdbook,wtbook_name):
        self.next.workbook(rdbook,'temp.xls')
        
    def row(self,rdrowx,wtrowx):
        self.pending_row = (rdrowx,wtrowx)

    def sheet(self,rdsheet,wtsheet_name):
        self.rdsheet = rdsheet
        self.wtrowxi = 0
        self.next.sheet(rdsheet,wtsheet_name)

    def cell(self,rdrowx,rdcolx,wtrowx,wtcolx):
        if rdcolx==0:
            value = self.rdsheet.cell(rdrowx,rdcolx).value
            if value.strip().lower()=='x':
                self.ignore_row = True
                q = self.z
                self.wtrowxi = self.counts[q]-1
                self.z = self.z+1
            else:
                self.ignore_row = False
                rdrowx, wtrowx = self.pending_row
                self.next.cell(
                rdrowx,rdcolx,wtrowx+self.wtrowxi,wtcolx
                )
        elif not self.ignore_row:
            self.next.cell(
                rdrowx,rdcolx,wtrowx+self.wtrowxi,wtcolx
                )


class R_Filter(BaseFilter):
    def workbook(self,rdbook,wtbook_name):
        self.next.workbook(rdbook,'temp.xls')